package c4.application.transactions.activities;

import java.util.Properties;

import c4.application.transactions.Activity;
import c4.application.transactions.ActivityResult;
import c4.application.transactions.CorporateDatabase;
import c4.application.transactions.Noss;
import c4.application.transactions.Resource;
import c4.common.Constants;
import java.util.Random;

public class ActivatePhoneServiceActivity extends Activity{

	public ActivatePhoneServiceActivity(Properties props) {
		super(props);
	}

	public ActivityResult execute(Resource db, Resource noss) {
		ActivityResult result = new ActivityResult();
		String address;
		int ticketId;
		Random generator = new Random();
		
		ticketId = generator.nextInt();
		address = 	(String)parameters.getProperty(Constants.STREET) + ", " +
					(String)parameters.getProperty(Constants.CITY) + ", " +
					(String)parameters.getProperty(Constants.STATE) + " " +
					(String)parameters.getProperty(Constants.ZIP);
		
		String nossMessage = "";
		
		nossMessage += 	"<C4Message>\n\t<ServiceRequest name=\"Activate\" uid=\"" + ticketId + "\">\n\t" +
						"\t<Param name=\"Service\" value=\"Phone Line\"/>\n\t" +
						"\t<Param name=\"Location\" value=\"" + address + "\"/>\n\t" +
						"</ServiceRequest>\n" + "</C4Message>";
		
		Noss myNoss = (Noss) noss;
		myNoss.sendMessage(nossMessage);
		
		//wait for reply on JMS In Queue
		String samplePhone = "";
		int phoneArea = 0, phoneCity = 0, phoneLocation = 0;

		while (phoneArea < 100) {
			phoneArea = generator.nextInt();
			phoneArea = phoneArea % 1000;
		}
		
		while (phoneCity < 100) {
			phoneCity = generator.nextInt();
			phoneCity = phoneCity % 1000;
		}
		
		while(phoneLocation < 1000) {
			phoneLocation = generator.nextInt();
			phoneLocation = phoneLocation % 10000;
		}
		
		samplePhone = phoneArea + "-" + phoneCity + "-" + phoneLocation;
		
		//ensure no dashes are in phone number
		samplePhone = samplePhone.replace("-", "");
		
		//if get a response from noss within threshold time
			//log to database		
		CorporateDatabase database = (CorporateDatabase) db;
		String query = "";
		
		query += 	"INSERT INTO phone_number_listing " +
					"VALUES (" + samplePhone + "," + (String)parameters.getProperty(Constants.ACCOUNT_NUMBER) + ");"; 
		
		database.execute(query);
		
		//else
			//give return an error message to the customer
		result.setResult(0);
		
		return result;
	}

	 
	public String getType() {
		return null;
	}

}
